<template>
  <div class="mobile-content">
    <Sticky>
      <Search v-model.trim="searchForm.keyword" show-action placeholder="请输入搜索关键词" @search="onRefresh"
        @cancel="onRefresh" />
      <DropdownMenu>
        <DropdownItem v-model="searchForm.mediaType" :options="typeOptions" @change="onRefresh" />
        <DropdownItem v-model="pagination.sortOrder" :options="orderOptions" @change="onRefresh" />
        <!-- <DropdownItem title="筛选" ref="dItem">
          <Cell center title="未推送">
            <template #right-icon>
              <Switch v-model="searchForm['status[]']" active-value="unlink" inactive-value="" />
            </template>
          </Cell>
          <Cell center title="未链接" :border="false">
            <template #right-icon>
              <Switch v-model="searchForm['linkDir[]']" active-value="no" inactive-value="" />
            </template>
          </Cell>
          <div style="padding: 5px 16px;">
            <Button type="primary" block round @click="()=>{dItem.toggle();onRefresh()}">
              确 认
            </Button>
          </div>
        </DropdownItem> -->
      </DropdownMenu>
    </Sticky>
    <PullRefresh v-model="refreshing" @refresh="onRefresh">
      <List v-model:loading="loading" :finished="finished" finished-text="没有更多了" v-model:error="error"
        :error-text="errorText" @load="onLoad">
        <Cell v-for="item in list">
          <Card :title="item.title" :desc="item.year" :thumb="item.info.poster" @click="rowOp(item)">
            <template #tag>
              <van-tag v-if="item.mediaType==='movie'" color="#87d068">电影</van-tag>
              <van-tag v-if="item.mediaType==='tv'" color="#108ee9">电视剧</van-tag>
            </template>
            <template #price>
              <Space>
                <template v-if="item.mediaType==='movie'">
                  <van-tag v-if="item.status==='playable'" type="success">可播放</van-tag>
                  <van-tag v-else-if="item.status==='sub'" type="warning">订阅中</van-tag>
                  <van-tag v-else-if="item.status==='find'" type="warning">已找到</van-tag>
                  <van-tag v-else-if="item.status==='download'" type="warning">下载中</van-tag>
                </template>
                <template v-else>
                  <van-tag type="warning">订阅中</van-tag>
                </template>
                <van-tag type="success">
                  <van-icon name="video-o" />{{libraryName(item.libraryid)}}
                </van-tag>
              </Space>
            </template>
          </Card>
        </Cell>
      </List>
    </PullRefresh>
    <ActionSheet v-model:show="opShow" :actions="actions" cancel-text="取消" @select="rowSelect" />
    <div class="menu-btn">
      <Popover v-model:show="menuShow" :actions="menuActions" placement="left-end" @select="menuSelect">
        <template #reference>
          <Button round plain icon="bars" type="primary"></Button>
        </template>
      </Popover>
    </div>
  </div>
</template>
<script name="sub-mobile" setup>
import {
  Sticky, Search, DropdownMenu, DropdownItem, Switch, PullRefresh, List, Cell
  , Card, Space, Tag as vanTag, Rate as VanRate, ActionSheet, Button, Popover, Dialog
  , Notify, Icon as VanIcon
} from 'vant';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import BaseApi from '@/api/api.js';
import SubApi from '../../api/SubApi';

import store from '@/store';

const libraryOptions = store.state.libraryOptions;
const libraryName = (libraryid) => {
  const library = libraryOptions.find(item => item.id === libraryid);
  if (library) return library.name

  return '未知媒体库';
}

const router = useRouter();

const module = 'sub';
const list = ref([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const error = ref(false);
const errorText = ref('加载失败，请刷新重试');
const searchForm = reactive({
  keyword: '',
  mediaType: '',
});
const pagination = {
  current: 1,
  pageSize: 20,
  sortField: 'addtime',
  sortOrder: 'descend'
};

const orderOptions = [
  { text: '默认排序', value: 'descend' },
  { text: '时间正序', value: 'ascend' },
];
const typeOptions = [
  { text: '全部', value: '' },
  { text: '电影', value: 'movie' },
  { text: '剧集', value: 'tv' },
];
const dItem = ref(null);

const onLoad = () => {
  BaseApi.list(module, { ...searchForm, ...pagination }).then(response => {
    if (response.data.code === 1) {
      response.data.data.rows.forEach(item => {
        item.info = JSON.parse(item.info);
        list.value.push(item);
      });

      pagination.current += 1;

      if (list.value.length >= response.data.data.total) {
        finished.value = true;
      }
    } else {
      error.value = true;
      errorText.value = `数据加载失败：${response.data.message}`;
    }
  }).catch((error) => {
    error.value = true;
    errorText.value = `数据加载失败：${error.message}`;
  }).then(() => {
    loading.value = false;
  })
};

const onRefresh = () => {
  refreshing.value = false;

  // 清空列表数据
  pagination.current = 1;
  list.value = [];
  finished.value = false;

  error.value = false;
  errorText.value = '';
  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true;

  onLoad();
};

const subAction = (id) => {
  SubApi.action(id).then(response => {
      if (response.data.code === 1) {
        opShow.value = false;
        Notify({ type: 'success', message: '操作成功' });
      } else {
        Notify({ type: 'danger', message: `操作失败：${response.data.message}` });
      }
    }).catch((error) => {
      Notify({ type: 'danger', message: `操作失败：${error.message}` });
    }).then(() => {
    })
}

//
let opRow = undefined;
const oping = ref(false);
const opShow = ref(false);
const actions = [
  { name: '查看' },
  { name: '取消订阅', color: '#ee0a24' },
];
const rowOp = (item) => {
  opRow = item;
  opShow.value = true;
};
const rowSelect = (item, index) => {
  // 默认情况下点击选项时不会自动收起
  if (index === 0) {
    opShow.value = false;

    router.push({
      path: '/m/sub/detail',
      query: {
        tmdbid: opRow.tmdbid,
        type: opRow.mediaType
      }
    })
  } else if (index === 1) {
    Dialog.confirm({
      title: '确认取消订阅',
      message:
        '取消后不影响已有的下载和资源',
      beforeClose: toRemove,
    });
  }
};

const toRemove = (action) =>
  new Promise((resolve) => {
    if (action === 'confirm') {
      BaseApi.del(module, opRow.id).then(response=>{
        if (response.data.code === 1) {
          opShow.value = false;
          onRefresh();
          Notify({ type: 'success', message: '取消成功' });
        } else {
          Notify({ type: 'error', message: `取消失败：${response.data.message}` });
        }
      }).catch((error)=>{
        Notify({ type: 'error', message: `取消失败：${error.message}` });
      }).then(()=>{
        resolve(true);
      })
    } else {
      resolve(true);
    }
  });

const menuShow = ref(false);
const menuActions = [
  { text: '更新全部' },
];
const menuSelect = (action, index) => {
  if (index === 0) {
    subAction()
  } else if (index === 1) {
  }
};

  // init functions

</script>
<style scoped>
.row-title {}

.label-time {
  margin: 0;
  padding: 0;
}

.menu-btn {
  position: fixed;
  bottom: calc(20px + var(--van-tabbar-height));
  /* right: 20px; */
  width: 100%;
  text-align: right;
  padding-right: 20px;
}
</style>